package com.nic.view.util.download;

import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.nic.view.R;

import java.io.File;

/**
 * Created by Administrator on 2018/7/3.
 */

public class DownloadManagerUtil {
    private static String TAG = DownloadManagerUtil.class.getName();
    private long downloadId = 2333;
    private static DownloadManagerUtil managerUtil;


    public static DownloadManagerUtil getInstance() {
        if (managerUtil == null) {
            synchronized (DownloadManagerUtil.class) {
                managerUtil = new DownloadManagerUtil();
            }
        }
        return managerUtil;
    }


    public void loadApk(final Context mContext, String url) {
        int state = mContext.getPackageManager().getApplicationEnabledSetting(mContext.getPackageName());
        if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.Theme_AppCompat_Dialog_Alert).setTitle("温馨提示").setMessage
                    ("系统下载管理器被禁止，需手动打开").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    try {
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.setData(Uri.parse("package:" + mContext.getPackageName()));
                        mContext.startActivity(intent);
                    } catch (ActivityNotFoundException e) {
                        Intent intent = new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
                        mContext.startActivity(intent);
                    }
                }
            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.create().show();
            return;
        }
        if (url.startsWith("http") && url.endsWith(".apk")) {
            String apkName = url.substring(url.lastIndexOf("/") + 1, url.length());
            if (downloadId != 2333) {
                clearCurrentTask(mContext, downloadId);
            }
            downloadId = download(mContext, url, apkName);
        }

    }

    public long download(final Context mContext, String url, String apkName) {
        return download(mContext, url, apkName, "下载完成后，点击安装");
    }

    public long download(final Context mContext, String url, String title, String desc) {
        Uri uri = Uri.parse(url);
        DownloadManager.Request req = new DownloadManager.Request(uri);
        //设置WIFI下进行更新
        req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
        //下载中和下载完后都显示通知栏
        req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        //使用系统默认的下载路径 此处为应用内 /android/data/packages ,所以兼容7.0
        req.setDestinationInExternalFilesDir(mContext, Environment.DIRECTORY_DOWNLOADS, title);
        //通知栏标题
        req.setTitle(title);
        //通知栏描述信息
        req.setDescription(desc);
        //设置类型为.apk
        req.setMimeType("application/vnd.android.package-archive");
        //获取下载任务ID
        DownloadManager dm = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        return dm.enqueue(req);
    }

    /**
     * 下载前先移除前一个任务，防止重复下载
     *
     * @param downloadId
     */
    public void clearCurrentTask(final Context mContext, long downloadId) {
        DownloadManager dm = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        try {
            Uri downloadFileUri = dm.getUriForDownloadedFile(downloadId);
            removeOldApk(mContext, downloadFileUri);
            dm.remove(downloadId);
        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 删除上次更新存储在本地的apk
     */
    private void removeOldApk(final Context mContext, Uri downloadFileUri) {

        //获取老ＡＰＫ的存储路径
        File fileName = new File(downloadFileUri.getPath());
        Log.i(TAG, "老APK的存储路径 =" + downloadFileUri.getPath());

        if (fileName != null && fileName.exists() && fileName.isFile()) {
            fileName.delete();
            Log.i(TAG, "存储器内存在老APK，进行删除操作");
        }
    }


    //apk更新
    public void updateDialog(final Context mContext, final String apkUrl, String desc) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_view, null);
        final AlertDialog dialog = new AlertDialog.Builder(mContext, R.style.Theme_AppCompat_Dialog_Alert).setView(view).create();

        TextView tvTitle = (TextView) view.findViewById(R.id.title);
        tvTitle.setText("检测到新的版本可以更新！");
        TextView tvMsg = (TextView) view.findViewById(R.id.message);
        tvMsg.setText(desc);
        Button btConfirm = (Button) view.findViewById(R.id.confirm);
        btConfirm.setText("去更新");
        Button btMiddle = (Button) view.findViewById(R.id.bt_middle);
        btMiddle.setText("浏览器更新");
        btMiddle.setVisibility(View.GONE);
        Button btCancel = (Button) view.findViewById(R.id.cancel);
        btCancel.setText("取消");
        btConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (!TextUtils.isEmpty(apkUrl))
                    try {
                        loadApk(mContext, apkUrl);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
            }
        });
        btMiddle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (!TextUtils.isEmpty(apkUrl))
                    try {
                        webUpdate(mContext, apkUrl);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
            }
        });
        btCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
//                deleteAllActivity();
            }
        });
        dialog.setCancelable(false);
        dialog.show();
    }

    public void webUpdate(final Context mContext, String ApkUrl) {
        Uri uri = Uri.parse(ApkUrl);
        // 启动浏览器下载
        Intent intent = new Intent(
                Intent.ACTION_VIEW, uri);
        // 启动activity
        mContext.startActivity(intent);
    }
}
